package CSS::Parser::AsBuilder;
use Moose;
use Carp;

extends 'CSS::Parser::Base';

use lib '../../../lib';
use CSS::Builder::Document;
use CSS::Builder::Property;
use CSS::Parser::AsBuilder::Selectors;
use CSS::Parser::AsBuilder::Styles;

sub parse_string {
    my ($self , $string) = @_;
    
    $string =~ s/\r\n|\r|\n/ /g;
    
    my $doc = CSS::Builder::Document->new;
    
    # Split into styles
    foreach ( grep { /\S/ } split /(?<=\})/, $string ) {
	unless ( /^\s*([^{]+?)\s*\{(.*)\}\s*$/ ) {
	    croak( "Invalid or unexpected style data '$_'" );
	}
	$doc->push($self->create_style($1, $2));
    }
    
    return $doc;
}

# add a style to the style list
sub create_style {
    my ($self , $selectors , $styles) = @_;
    
    # new propery containing selectors and styles
    my $property = CSS::Builder::Property->new;
    
    # build list of selectors
    my $sel = CSS::Parser::AsBuilder::Selectors->new;
    $property->selectors($sel->build_selectors($selectors));
    
    # build list of contents
    my $sty = CSS::Parser::AsBuilder::Styles->new;
    $property->list($sty->build_styles($styles));
    
    # return property
    return $property;
}

1;